import * as THREE from '../../build/three.module.js';
import Stats from '../../jsm/libs/stats.module.js';

import { OrbitControls } from '../../jsm/controls/OrbitControls.js';
import { GLTFLoader } from '../../jsm/loaders/GLTFLoader.js';

const scene = new THREE.Scene();
scene.background = new THREE.Color(0xa0a0a0);
scene.fog = new THREE.Fog(0xa0a0a0, 70, 100); // 雾：颜色、开始应用雾的最小距离、结束计算、应用雾的最大距离（1000）

const k = innerWidth / innerHeight,
      s = 45,
      camera = new THREE.PerspectiveCamera(s, k, 1, 1000);
camera.position.set(24, 8, 24);

const clock = new THREE.Clock(); // 唯一参数 autoStart: Boolean 是否默认开始计时，默认为 true

// 背景
const geometry = new THREE.PlaneBufferGeometry(500, 500);
const material = new THREE.MeshPhongMaterial({ color: 0x999999, depthWrite: false });

const groundMesh = new THREE.Mesh(geometry, material);
groundMesh.position.set(0, -5, 0);
groundMesh.rotation.x = - Math.PI / 2;
groundMesh.receiveShadow = true; // 接收阴影
scene.add(groundMesh);

const grid = new THREE.GridHelper(500, 100, 0x000000, 0x000000);
grid.position.y = -5;
grid.material.opacity = .2;
grid.material.transparent = true;
scene.add(grid);

// 光源
let light = new THREE.HemisphereLight(0xffffff, 0x444444, .6); // 半球光 —— 提亮场景
light.position.set(0, 200, 0);
scene.add(light);

light = new THREE.DirectionalLight(0xffffff, .8); // 平行光 —— 投射阴影
light.position.set(0, 20, 10);
light.castShadow = true; // 动态阴影
light.shadow.camera.top = 18;
light.shadow.camera.bottom = -10;
light.shadow.camera.left = -12;
light.shadow.camera.right = 10;
scene.add(light);

// 加载模型
const loader = new GLTFLoader();
let mixer = null;
loader.load('../../models/gltf/SimpleSkinning.gltf', gltf => {
  scene.add(gltf.scene);

  gltf.scene.traverse(child => {
    if (child.isSkinnedMesh) child.castShadow = true;
  });

  mixer = new THREE.AnimationMixer(gltf.scene);
  mixer.clipAction(gltf.animations[0]).play();
})

// 渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(devicePixelRatio); // 避免HiDPI设备上绘图模糊
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true; // 启用阴影贴图 —— 次示例中阴影贴图来自于加载的外部模型
document.body.appendChild(renderer.domElement);

// 性能统计
const stats = new Stats();
document.body.appendChild(stats.dom);

// 交互控制
const controls = new OrbitControls(camera, renderer.domElement);
controls.enablePan = false; // 禁止右键拖拽
controls.minDistance = 5;
controls.maxDistance = 50;

(function render() {

  requestAnimationFrame(render);

  if (mixer) mixer.update(clock.getDelta());

  renderer.render(scene, camera);
  stats.update();

})();